<template>
  <div id="login_container"></div>
</template>

<script>
import { removeEvent } from '@/utils/removeEvent'

export default {
  name: 'DingTalkLogin',
  data () {
    return {
      handleMessage: null
    }
  },
  methods: {
    codeLogin () {
      // eslint-disable-next-line no-undef
      DDLogin({
        id: 'login_container',
        // goto这里需要对url整体做一个urlencode编码
        goto: encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoap5khgsxhpwuea7ar&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=https://135680.xyz'),
        style: 'border:none;background-color:#FFFFFF;',
        width: '300',
        height: '300'
      })

      this.handleMessage = function (event) {
        const origin = event.origin
        // 判断是否来自ddLogin扫码事件
        if (origin === 'https://login.dingtalk.com') {
          const loginTmpCode = event.data
          // 这里url不用进行urlencode编码
          const url = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoap5khgsxhpwuea7ar&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=135680.xyz&loginTmpCode=' + loginTmpCode
          window.location.href = url
        }
      }

      if (typeof window.addEventListener !== 'undefined') {
        window.addEventListener('message', this.handleMessage, false)
      } else if (typeof window.attachEvent !== 'undefined') {
        window.attachEvent('onmessage', this.handleMessage)
      }
    }
  },
  mounted () {
    this.codeLogin()
  },
  beforeDestroy () {
    removeEvent(window, 'message', this.handleMessage)
  }
}
</script>

<style lang="scss" scoped>
::v-deep #login_container{
  .login_qrcode_content{
    margin-top: 0;
  }
}
</style>
